package com.shensi.appCollect.pay;

import com.shensi.appCollect.constantEnum.PayWayPayTypeEnum;
import com.shensi.appCollect.utils.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @date 2023/8/10
 */
@Component
public class PayChannelHandler implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger log = LoggerFactory.getLogger(PayChannelHandler.class);

    private Map<PayWayPayTypeEnum,PayChannel> channelMap;

    public PayChannel getPayChannel(PayWayPayTypeEnum typeEnum){
        PayChannel payChannel = channelMap.get(typeEnum);
        if (payChannel == null) {
            throw new CustomException("不支持改支付渠道");
        }
        return payChannel;
    }

    public PaymentStrategy getPaymentStrategy(PayWayPayTypeEnum typeEnum){
        return getPayChannel(typeEnum).getPayStrategy();
    }

    public QueryOrderStrategy getQueryOrderStrategy(PayWayPayTypeEnum typeEnum){
        return getPayChannel(typeEnum).getQueryOrderStrategy();
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext context = contextRefreshedEvent.getApplicationContext();
        PayWayPayTypeEnum[] values = PayWayPayTypeEnum.values();
        channelMap = new HashMap<>();
        for (PayWayPayTypeEnum value : values) {
            Class<? extends PayChannel> channelClass = value.getChannelClass();
            if (channelClass == null) {
                continue;
            }
            PayChannel bean = context.getBean(channelClass);
            bean.init();
            channelMap.put(value, bean);
        }
    }
}
